package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import jakarta.annotation.Resource;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;
    @Override
    public Result queryById(Long id) {
        // 缓存穿透
//        Shop shop = queryWithPassThrough(id);
        Shop shop = cacheClient
                .queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 缓存击穿
//        Shop shop = queryWithMutex(id);
        // 逻辑过期解决缓存击穿，需要数据预热
//        Shop shop = queryWithLogicalExpire(id);
//        Shop shop = cacheClient
//                .queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        if(shop == null){
            return Result.fail("店铺不存在！");
        }
        return Result.ok(shop);
    }

    // 缓存击穿 - 设置空对象
    public Shop queryWithMutex(Long id){
        // 1、检查在redis中是否存在该商店
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        Shop shop;
        // 2、存在则直接查
        if(StrUtil.isNotBlank(shopJson)){
            shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        // 判断命中的是否为空值， 特判一下空对象
        if(shopJson != null){
            return null;
        }
        // 3、不存在则查数据库
        String lockKey = LOCK_SHOP_KEY + id;
        // 3.1 查询互斥锁是否被占用
        try {
            boolean flag = tryLock(lockKey);
            // 3.2 若被占用则休眠并再次调用函数
            if(!flag){
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            // 3.3 未占用则占用锁并进行后续查询和更新缓存操作
            shop = getById(id);
            // 模拟延迟
            Thread.sleep(200);
            // 4、数据库中不存在该用户则直接返回
            if(shop == null){
                // 防止缓存穿透，设立空对象
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            // 5、更新缓存
            String jsonShop = JSONUtil.toJsonStr(shop);
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, jsonShop, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (Exception e){
            throw new RuntimeException(e);
        } finally {
            // 6、删除锁
            delLock(lockKey);
        }
        // 7、返回
        return shop;
    }

    // 缓存穿透 - 互斥锁
    public Shop queryWithPassThrough(Long id) {
        // 1、检查在redis中是否存在该商店
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        // 2、存在则直接查
        if(StrUtil.isNotBlank(shopJson)){
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        // 判断命中的是否为空值， 特判一下空对象
        if(shopJson != null){
            return null;
        }
        // 3、不存在则查数据库
        Shop shop = getById(id);
        // 4、数据库中不存在该用户则直接返回
        if(shop == null){
            // 防止缓存穿透，设立空对象
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 5、返回
        String jsonShop = JSONUtil.toJsonStr(shop);
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, jsonShop, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return shop;
    }

    // 存逻辑过期的redis数据
    public void saveShop2Redis(Long id, Long expireSeconds){
        Shop shop = getById(id);
        // 封装为带有逻辑过期时间的shop对象
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 存入缓存
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    // 逻辑过期解决缓存击穿
    public Shop queryWithLogicalExpire(Long id){
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        // 2、存在则直接查
        if(StrUtil.isBlank(shopJson)){
            return null;
        }
        // 3、反序列化redis中数据为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        // 4、判断逻辑是否过期
        LocalDateTime expireTime = redisData.getExpireTime();
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        // 4.1 未过期则直接返回商铺信息
        if(expireTime.isAfter(LocalDateTime.now())){
            return shop;
        }
        // 4.2 过期则进行缓存重建

        // 5 缓存重建
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        // 5.1 尝试获取互斥锁，若成功获取互斥锁，则开启新线程进行逻辑时期更新和缓存重建
        if(isLock){
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    this.saveShop2Redis(id, 20L);
                } catch (Exception e) {
                   throw new RuntimeException(e);
                }finally {
                    // 释放锁
                    delLock(lockKey);
                }
            });
        }

        // 5.2 失败，则直接返回店铺信息
        return shop;
    }

    @Override
    public Result update(Shop shop) {
        Long id = shop.getId();
        if(id == null){
            return Result.fail("店铺id不能为空");
        }
        // 1、更新数据库
        updateById(shop);
        // 2、删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);

        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1.判断是否需要距离服务
        if(x == null || y == null){
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));

            return Result.ok(page.getRecords());
        }
        // 2.计算分页参数
        String key = SHOP_GEO_KEY + typeId;
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE; // 当前分页起始端
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        // 3.从缓存取出当前分页店铺
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );
        // 4.从ScrollResult解析出list，截取从from到end的店铺信息
        if(results == null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        // 特判当list中（即到end）的店铺数量少于或等于当前页码的from，则返回空
        if(list.size() <= from){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result->{
            // 4.1店铺id
            String shopId = result.getContent().getName();
            ids.add(Long.valueOf(shopId));
            // 4.2 店铺坐标（经处理）
            Distance distance = result.getDistance();
            distanceMap.put(shopId, distance);
        });
        // 5.1 按set顺序查询店铺
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        // 5.2 为所有shop属性都附上distance
        for (Shop shop : shops) {
            // 获取店铺距离
            Distance distance = distanceMap.get(shop.getId().toString());
            // 赋值
            shop.setDistance(distance.getValue());
        }

        return Result.ok(shops);
    }

    private boolean tryLock(String key){
        // 最好按实际处理时间来设置过期时间
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void delLock(String key){
        stringRedisTemplate.delete(key);
    }
}
